const app = getApp()
var server = require('../../utils/server');
var common = require('../../utils/common');
var amapFile = require('../../libs/amap-wx.js');
var gdMap = new amapFile.AMapWX({
  key: common.gdKey
});
Page({
  data: {
    cartNum: 0,
    goods_id: "",
    storeId: "",
    storageStoreid: '',
    goodsDetail: '',
    showLoginPop: false,
    isCanAdd: true,
    isCanReduce: true,
    isLocate: true,
    isShowExchange: false,
    isCanExchange: true,
    scene: '',
    isShowHome: false,
    isLogin: false,
    timestap: 0,
    goodscode: '',
    userParams: {},
    channelId: "", //渠道ID
    isDisableLog: false,
    isExchange: false
  },
  onLoad(options = {}) {
    console.log(options)
    if(options.scene=='gzh'){//判断是否从公众号或者分享页进入
      this.data.storeId = options.storeId;
    }
    this.data.goods_id = options.id == undefined ? '' : options.id;
    this.data.channelId = options.cid == undefined ? '' : options.cid;
    this.data.scene = options.scene == undefined ? '' : options.scene;
    this.data.goodscode = options.code == undefined ? '' : options.code;
    this.data.categoryid = options.categoryid == undefined ? '' : options.categoryid;
    app.globalData.refreshTag = app.globalData.isFromHome ? true : false;
    if (options.scene != undefined || app.globalData.isFromHome) {
      app.globalData.refreshTag = true;
      this.setData({
        isShowHome: true
      })
    }

  },
  onHide() {
    wx.removeStorage({
      key: 'curgoodsmesg',
      success: function (res) {
      },
    })

  },
  onShow() {
    this.data.storageStoreid = wx.getStorageSync('storeId');
    this.setData({
      timestap: Date.parse(new Date())
    })
    wx.showShareMenu({
      withShareTicket: true
    })
    if (app.globalData.isLocate || this.data.isLocate) {
      this.getUserInfo();
      this.setData({
        isLocate: app.globalData.isLocate
      })
    }
  },
  //解析scene
  decodeScene(scene) {
    server.postJSON(common.storePath + 'voucher/scenedecode/', {
      "scene": scene
    }, res => {
      var data = res.data.data;
      if (res.data.errno == '0') {
        wx.setStorage({
          key: 'companyid',
          data: data.company_id,
        })
        this.data.goods_id = data.goods_id;
        this.data.storeId = data.store_id;
        var param = {
          "city": app.globalData.city,
          "longitude": app.globalData.longitude,
          "latitude": app.globalData.latitude,
          "store_id": this.data.storeId == 0 ? '' : this.data.storeId,
          "goods_id": this.data.goods_id
        }
        server.postJSON(common.storePath + 'goods/detail/', param, res => {
          var res = res.data;
          if (res.errno == "0") {
            wx.hideNavigationBarLoading();
            common.hideLoading();
            this.setData({
              goodsDetail: res.data
            })
            this.data.storeId = res.data.store.store_id;
            app.globalData.city = res.data.store.city;
            app.globalData.skipType = 2;
            wx.setStorage({
              key: 'storeId',
              data: res.data.store.store_id,
              success: res => {
              }
            })
            this.getCartNum();
            this.getRecommendGoods();
            if (res.data.cart_num > 0) {
              this.setData({
                isCanReduce: true
              })
            }
            this.setData({
              isCanAdd: true
            })
          } else if (res.errno == "153001") {
            common.showErrorToast(res.errmsg)
            if (this.data.storageStoreid == '' || this.data.storageStoreid == undefined) {
              app.globalData.skipType = 1;
            } else {
              app.globalData.skipType = 2;
            }
            setTimeout(function () {
              wx.switchTab({
                url: '../index/index',
              })
            }, 1000)
          } else {
            common.showErrorToast(res.errmsg)
          }

        })
        if (data.channel_id != '') {
          this.data.channelId = data.data.channel_id;
          wx.setStorage({
            key: 'channelid',
            data: data.channel_id
          })
        }
      } else {
        common.showErrorToast(res.data.errmsg);
      }
    })
  },
  getProductDetail() {
    this.data.formSceneId = app.globalData.formSceneId;
    app.globalData.isFromCart = this.data.scene == 'gzh' ? false : app.globalData.isFromCart;
    if (this.data.scene == 'gzh' && !app.globalData.isFromCart && this.data.storeId == '') {
      this.locateCur();
    } else if (this.data.scene != '' && this.data.scene.indexOf('DECODE') > -1) {
      this.locateCur();
    } else if (app.globalData.isFromCart) {
      var param = {
        "city": app.globalData.city,
        "longitude": app.globalData.longitude,
        "latitude": app.globalData.latitude,
        "store_id": this.data.storageStoreid,
        "goods_id": this.data.goods_id,
        "code": this.data.goodscode
      }
      this.getDetail(param);
    } else {
      if (this.data.storageStoreid == '' && this.data.storeId != '') {
        var param = {
          "city": app.globalData.city,
          "longitude": app.globalData.longitude,
          "latitude": app.globalData.latitude,
          "store_id": this.data.storeId,
          "goods_id": this.data.goods_id,
          "code": this.data.goodscode
        }
      } else if (this.data.storageStoreid != '' && this.data.storeId == '') {
        var param = {
          "city": app.globalData.city,
          "longitude": app.globalData.longitude,
          "latitude": app.globalData.latitude,
          "store_id": this.data.storageStoreid,
          "goods_id": this.data.goods_id,
          "code": this.data.goodscode
        }
      } else if (this.data.storageStoreid != '' && this.data.storeId != '') {
        var param = {
          "city": app.globalData.city,
          "longitude": app.globalData.longitude,
          "latitude": app.globalData.latitude,
          "store_id": this.data.storeId,
          "goods_id": this.data.goods_id,
          "code": this.data.goodscode
        }
      }
      this.getDetail(param);
    }
    app.globalData.isLocate = true;
    this.setData({
      isLocate: true
    })
  },
  locateCur() {
    common.showLoading();
    common.hideLoading();
    if (app.globalData.longitude == null || app.globalData.latitude == null || app.globalData.city == null) {
      app.globalData.longitude = this.data.templongitude;
      app.globalData.latitude = this.data.templatitude;
      app.globalData.city = this.data.tempcity;
    }
    if (!app.globalData.isGetCartByAdd && this.data.storageStoreid == '') {
      app.globalData.addrId = null;
    }
    app.globalData.isGetCartByAdd = false;
    if (this.data.scene != '' && this.data.scene.indexOf('DECODE') > -1) {
      this.decodeScene(this.data.scene);
    } else {
      console.log(this.data.storeId)
      var curgoodsmesg = wx.getStorageSync('curgoodsmesg');
      this.data.trace_id = curgoodsmesg.curtraceid == undefined ? '' : curgoodsmesg.curtraceid;
      this.data.goodsscene = curgoodsmesg.curgoodsscene == undefined ? '' : curgoodsmesg.curgoodsscene;
      var param = {
        "goods_id": this.data.goods_id,
        "city": app.globalData.locateCity,
        "longitude": app.globalData.locateLongitude,
        "latitude": app.globalData.locateLatitude,
        "store_id": this.data.storeId,
        "trace_id": curgoodsmesg.curtraceid == undefined ? '' : curgoodsmesg.curtraceid,
        "scene": curgoodsmesg.curgoodsscene == undefined ? '' : curgoodsmesg.curgoodsscene,
        "code": this.data.goodscode
      }
      server.postJSON(common.storePath + 'goods/detail/', param, res => {
        var res = res.data;
        if (this.data.channelId != '') {
          wx.setStorage({
            key: 'channelid',
            data: this.data.channelId
          })
        }
        if (res.errno == "0") {
          wx.hideNavigationBarLoading();
          common.hideLoading();
          this.setData({
            goodsDetail: res.data
          })
          this.data.storeId = res.data.store.store_id;
          app.globalData.city = res.data.store.city;
          wx.setStorage({
            key: 'storeId',
            data: res.data.store.store_id,
            success: res => {
            }
          })
          this.getCartNum();
          this.getRecommendGoods();
          if (res.data.cart_num > 0) {
            this.setData({
              isCanReduce: true
            })
          }
          this.setData({
            isCanAdd: true
          })
        } else if (res.errno == "153001") {
          common.showErrorToast(res.errmsg)
          if (this.data.storageStoreid == '' || this.data.storageStoreid == undefined) {
            app.globalData.skipType = 1;
          } else {
            app.globalData.skipType = 2;
          }
          setTimeout(function () {
            wx.switchTab({
              url: '../index/index',
            })
          }, 1000)

        } else {
          common.showErrorToast(res.errmsg)
        }

      })
    }
  },
  // 打开定位
  openLocation(e) {
    if (e.detail.errMsg == "openSetting:ok" && e.detail.authSetting['scope.userLocation']) {
      app.globalData.isLocate = true;
      this.setData({
        isLocate: true
      })
      this.getUserInfo();
      this.getCartNum();
    } else {
      this.setData({
        isLocate: false
      })
      common.showErrorToast('需要授权地理位置后使用！');
    }
  },
  getDetail(param) {
    wx.showNavigationBarLoading();
    console.log(param)
    if (param.store_id == '') {
      this.locateCur();
    } else {
      var curgoodsmesg = wx.getStorageSync('curgoodsmesg');
      this.data.trace_id = curgoodsmesg.curtraceid == undefined ? '' : curgoodsmesg.curtraceid;
      this.data.goodsscene = curgoodsmesg.curgoodsscene == undefined ? '' : curgoodsmesg.curgoodsscene;
      param.trace_id = curgoodsmesg.curtraceid == undefined ? '' : curgoodsmesg.curtraceid;
      param.scene = curgoodsmesg.curgoodsscene == undefined ? '' : curgoodsmesg.curgoodsscene;
      server.postJSON(common.storePath + 'goods/detail/', param, res => {
        var res = res.data;
        if (this.data.channelId != '') {
          wx.setStorage({
            key: 'channelid',
            data: this.data.channelId
          })
        }
        if (res.errno == "0") {
          wx.hideNavigationBarLoading();
          common.hideLoading();
          this.setData({
            goodsDetail: res.data
          })
          this.data.storeId = res.data.store.store_id;
          app.globalData.city = res.data.store.city;
          this.getCartNum();
          this.getRecommendGoods();
          wx.setStorage({
            key: 'storeId',
            data: res.data.store.store_id,
            success: res => {
            }
          })
          app.globalData.skipType = 2; //从详情回去是否定位当前门店
          if (res.data.cart_num > 0) {
            this.setData({
              isCanReduce: true
            })
          }
          this.setData({
            isCanAdd: true
          })
        } else if (res.errno == "153001") {
          common.showErrorToast(res.errmsg)
          if (this.data.storageStoreid == '' || this.data.storageStoreid == undefined) {
            app.globalData.skipType = 1;
          } else {
            app.globalData.skipType = 2;
          }
          setTimeout(function () {
            wx.switchTab({
              url: '../index/index',
            })
          }, 1000)

        } else {
          common.showErrorToast(res.errmsg)
        }

      })
    }
  },
  //获取购物车数量
  getCartNum() {
    server.postJSON(common.storePath + 'cart/goodsnum', {
      "store_id": this.data.storeId,
      "is_deliverable": 0
    }, res => {
      if (res.data.errno == '0') {
        this.setData({
          cartNum: res.data.data.cart.num,
          cartPrice: res.data.data.cart.amount
        })
      } else {
        common.showErrorToast(res.data.errmsg);
      }
    })
  },
  //手动输入数字
  updateGoodsNum(e) {
    var goodnum = e.detail.value,
      goodsid = e.currentTarget.dataset.id;
    if (this.data.isLogin) {
      if (this.data.goodsDetail.cart_num > 0 && parseInt(goodnum) >= 1) {
        server.postJSON(common.storePath + 'cart/updatedetail/', {
          "store_id": this.data.storeId,
          "goods_id": goodsid,
          "longitude": app.globalData.longitude,
          "latitude": app.globalData.latitude,
          "quantity": goodnum
        }, res => {
          if (res.data.errno == "0") {
            this.data.goodsDetail.cart_num = parseInt(goodnum);
            this.setData({
              goodsDetail: this.data.goodsDetail
            })
            this.storageUpdateGoods(this.data.storeId, e.currentTarget.dataset.id, parseInt(goodnum));
            this.getCartNum();
          } else {
            this.setData({
              goodsDetail: this.data.goodsDetail
            })
            common.showErrorToast(res.data.errmsg);
          }
        })
      } else if (this.data.goodsDetail.cart_num == 0 && parseInt(goodnum) == 1) {
        let goodsDetail = this.data.goodsDetail;
        this.setData({
          isCanAdd: false
        })
        server.postJSON(common.storePath + 'cart/addgoods/', {
          "store_id": this.data.storeId,
          "goods_id": e.currentTarget.dataset.id,
          "trace_id": this.data.trace_id,
          "scene": this.data.goodsscene
        }, res => {
          if (res.data.errno == "0") {
            common.showErrorToast("添加成功");
            goodsDetail.cart_num = parseInt(goodsDetail.cart_num) + 1;
            this.setData({
              goodsDetail: goodsDetail,
              cartNum: parseInt(this.data.cartNum) + 1,
              isCanAdd: true
            })
            this.getCartNum();
            this.storageUpdateGoods(this.data.storeId, e.currentTarget.dataset.id, parseInt(goodsDetail.cart_num));
          } else {
            this.setData({
              isCanAdd: true
            })
            common.showErrorToast(res.data.errmsg);
          }
        })
      }
    } else {
      this.setData({
        showLoginPop: true
      })
    }
  },
  getCurGoodsNum(e) {
    var goodnum = e.detail.value,
      goodsid = e.currentTarget.dataset.id;
    if (goodnum == '') {
      server.postJSON(common.storePath + 'cart/updatedetail/', {
        "store_id": this.data.storeId,
        "goods_id": goodsid,
        "longitude": app.globalData.longitude,
        "latitude": app.globalData.latitude,
        "quantity": 1
      }, res => {
        if (res.data.errno == "0") {
          this.data.goodsDetail.cart_num = 1;
          this.setData({
            goodsDetail: this.data.goodsDetail
          })
          this.storageUpdateGoods(this.data.storeId, e.currentTarget.dataset.id, 1);
          this.getCartNum();
        } else {
          this.setData({
            goodsDetail: this.data.goodsDetail
          })
          common.showErrorToast(res.data.errmsg);
        }
      })
    }
  },

  // 添加购物车
  addCart() {
    let goodsDetail = this.data.goodsDetail;
    this.setData({
      isCanAdd: false
    })
    if (this.data.isLogin) {
      server.postJSON(common.storePath + 'cart/addgoods/', {
        "store_id": this.data.storeId,
        "goods_id": goodsDetail.goods_id,
        "trace_id": this.data.trace_id,
        "scene": this.data.goodsscene
      }, res => {
        if (res.data.errno == "0") {
          common.showErrorToast("添加成功");
          goodsDetail.cart_num = parseInt(goodsDetail.cart_num) + 1;
          this.setData({
            goodsDetail: goodsDetail,
            cartNum: parseInt(this.data.cartNum) + 1,
            isCanAdd: true
          })
          this.getCartNum();
          this.storageUpdateGoods(this.data.storeId,goodsDetail.goods_id, parseInt(goodsDetail.cart_num));
        } else {
          this.setData({
            isCanAdd: true
          })
          if (res.data.errno == '100012') {
            this.setData({
              showLoginPop: true
            })
          } else {
            common.showErrorToast(res.data.errmsg);
          }
        }
      })
    } else {
      this.setData({
        showLoginPop: true,
        isCanAdd: true
      })
    }
  },
  //商品减1
  reduceCart(e) {
    let goodsDetail = this.data.goodsDetail;
    this.setData({
      isCanReduce: false
    })
    server.postJSON(common.storePath + 'cart/decrease/', {
      "store_id": this.data.storeId,
      "goods_id": e.currentTarget.dataset.id

    }, res => {
      this.setData({
        isCanReduce: true
      })
      if (res.data.errno == "0") {
        goodsDetail.cart_num = parseInt(goodsDetail.cart_num) - 1;
        this.setData({
          goodsDetail: goodsDetail,
          cartNum: parseInt(this.data.cartNum) - 1
        })
        this.getCartNum();
        this.storageUpdateGoods(this.data.storeId, e.currentTarget.dataset.id, parseInt(goodsDetail.cart_num));
      } else {
        common.showErrorToast(res.data.errmsg);
      }
    })
  },
  onShareAppMessage(options) {
    var fromType = options.from;
    if (typeof (this.data.goodsDetail.retail_price) == "number" && JSON.stringify(this.data.goodsDetail.retail_price).indexOf('.') > -1) {
      var array = JSON.stringify(this.data.goodsDetail.retail_price).split('.');
      var newArray = array[0] + '.' + array[1].substring(0, 2)
      this.data.goodsDetail.retail_price = newArray;
      this.setData({
        goodsDetail: this.data.goodsDetail
      })
    } else if (typeof (this.data.goodsDetail.retail_price) == "string" && this.data.goodsDetail.retail_price.indexOf('.') > -1) {
      var array = this.data.goodsDetail.retail_price.split('.');
      var newArray = array[0] + '.' + array[1].substring(0, 2)
      this.data.goodsDetail.retail_price = newArray;
      this.setData({
        goodsDetail: this.data.goodsDetail
      })
    } else {
      this.data.goodsDetail.retail_price = parseInt(this.data.goodsDetail.retail_price);
      this.setData({
        goodsDetail: this.data.goodsDetail
      })
    }
    var img = this.data.goodsDetail.pic_url + '-goods_share';
    var shareObj = {
      title: '￥' + this.data.goodsDetail.retail_price + ' | ' + this.data.goodsDetail.name,
      path: '/pages/shop/productDetail?code=' + this.data.goodsDetail.code + '&&storeId=' + this.data.goodsDetail.store.store_id +'&&scene=gzh&&cid=' + this.data.channelId,
      imageUrl: img,
      success: function (res) {
        var shareTickets = res.shareTickets == undefined ? '' : res.shareTickets[0];
        if (shareTickets != '') {
          wx.getShareInfo({
            shareTicket: shareTickets,
            success: ret => {
            }
          })
        }
      },
      fail: function () {
        console.log("分享失败")
      }
    }
    console.log(shareObj)
    return shareObj;
  },
  backHome() {
    app.globalData.skipType = 2;
    wx.switchTab({
      url: '../index/index',
    })
  },
  //获取用户信息
  getUserInfo() {
    var that = this;
    if (app.globalData.location == null) {
      gdMap.getRegeo({
        success: res => {
          app.globalData.isLocate = true;
          this.setData({
            isLocate: true
          })
          app.globalData.locateLongitude = res[0].longitude;
          app.globalData.locateLatitude = res[0].latitude;
          app.globalData.locateCity = res[0].regeocodeData.addressComponent.city;
          app.globalData.locateProvince = res[0].regeocodeData.addressComponent.province;
          app.globalData.location = res[0].regeocodeData.pois[0] == undefined ? res[0].name : res[0].regeocodeData.pois[0].name;
          this.data.templongitude = res[0].longitude;
          this.data.templatitude = res[0].latitude;
          this.data.tempcity = res[0].regeocodeData.addressComponent.city;
          wx.login({
            success: resp => {
              wx.getUserInfo({
                success: res => {
                  var code = resp.code;
                  this.data.userParams = {
                    "js_code": code,
                    "encryptedData": res.encryptedData,
                    "iv": res.iv,
                    "userinfo": res.userInfo,
                    "longitude": app.globalData.locateLongitude,
                    "latitude": app.globalData.locateLatitude,
                    "province": app.globalData.locateProvince,
                    "city": app.globalData.locateCity
                  }
                  var that = this;
                  server.login(common.basePath + 'miniprogram/login/', that.data.userParams, function (res) {
                    if (res.data.errno == "0") {
                      app.globalData.sso = res.data.data.sso;
                      app.globalData.openid = res.data.data.openid;
                      wx.setStorage({
                        key: "sso",
                        data: res.data.data.sso,
                        success: res => {
                          that.getProductDetail();
                        }
                      })
                      that.setData({
                        isLogin: true
                      })
                    } else {
                      that.setData({
                        isLogin: false
                      })
                      common.showErrorToast(res.data.errmsg);
                    }
                  })
                },
                fail: resp => {
                  var param = {
                    "city": app.globalData.city,
                    "longitude": app.globalData.longitude,
                    "latitude": app.globalData.latitude,
                    "store_id": this.data.storeId,
                    "goods_id": this.data.goods_id,
                    "code": this.data.goodscode
                  }
                  this.setData({
                    isLogin: false
                  })
                  this.getDetail(param);
                }
              })
            },
            fail: res => {
              this.setData({
                isLogin: false
              })
            }
          })
        },
        fail: info => {
          this.setData({
            isLocate: false
          })
          app.globalData.isLocate = false;
        }
      })
    } else {
      wx.login({
        success: resp => {
          wx.getUserInfo({
            success: res => {
              var code = resp.code;
              this.data.userParams = {
                "js_code": code,
                "encryptedData": res.encryptedData,
                "iv": res.iv,
                "userinfo": res.userInfo,
                "longitude": app.globalData.locateLongitude,
                "latitude": app.globalData.locateLatitude,
                "province": app.globalData.locateProvince,
                "city": app.globalData.locateCity
              }
              var that = this;
              server.login(common.basePath + 'miniprogram/login/', that.data.userParams, function (res) {
                if (res.data.errno == "0") {
                  app.globalData.sso = res.data.data.sso;
                  app.globalData.openid = res.data.data.openid;
                  wx.setStorage({
                    key: "sso",
                    data: res.data.data.sso,
                    success: res => {
                      that.getProductDetail();
                    }
                  })
                  that.setData({
                    isLogin: true
                  })
                } else {
                  that.setData({
                    isLogin: false
                  })
                  common.showErrorToast(res.data.errmsg);
                }
              })
            },
            fail: resp => {
              if (app.globalData.city == '' || app.globalData.longitude || app.globalData.latitude) {
                this.locateCur();
              } else {
                var param = {
                  "city": app.globalData.city,
                  "longitude": app.globalData.longitude,
                  "latitude": app.globalData.latitude,
                  "store_id": this.data.storeId,
                  "goods_id": this.data.goods_id,
                  "code": this.data.goodscode
                }
                this.getDetail(param);
              }
              this.setData({
                isLogin: false
              })
            }
          })
        },
        fail: res => {
          this.setData({
            isLogin: false
          })
        }
      })
    }
  },
  login(e) {
    this.setData({
      isDisableLog: true
    })
    if (e.detail.errMsg == "getUserInfo:ok") {
      this.setData({
        showLoginPop: false,
        isLogin: true
      })
      var that = this
      wx.login({
        success: resp => {
          wx.getUserInfo({
            success: res => {
              var code = resp.code;
              this.data.userParams = {
                "js_code": code,
                "encryptedData": res.encryptedData,
                "iv": res.iv,
                "userinfo": res.userInfo,
                "longitude": app.globalData.longitude,
                "latitude": app.globalData.latitude,
                "province": app.globalData.locateProvince,
                "city": app.globalData.city
              }
              var that = this;
              server.login(common.basePath + 'miniprogram/login/', this.data.userParams, function (res) {
                if (res.data.errno == "0") {
                  app.globalData.openid = res.data.data.openid;
                  wx.setStorage({
                    key: "sso",
                    data: res.data.data.sso,
                    success: res => {
                      that.setData({
                        isDisableLog: false
                      })
                      app.globalData.isGetWxUserinfo = true;
                      that.getProductDetail();
                    }
                  })
                } else {
                  that.setData({
                    isDisableLog: false
                  })
                  common.showErrorToast(res.data.errmsg)
                }
              })
            }
          })
        }
      })

    } else {
      this.setData({
        isDisableLog: false
      })
      wx.showToast({
        icon: 'none',
        title: '需要授权用户信息使用元初到家！'
      })
    }
  },
  //本地存储用户信息
  storageUserinfo(data) {
    wx.setStorage({
      key: "userInfo",
      data: data
    })
  },
  storageUpdateGoods(storeid, goodsid, num) {
    var storeArry = new Array();
    wx.getStorage({
      key: 'updateStoreArry',
      success: res => {
        storeArry = res.data;
        var t = storeArry.find(item => {
          return item.goodsid == goodsid;
        });
        if (t) {
          t.goodsnum = num;
        } else {
          storeArry.push({
            goodsid: goodsid,
            goodsnum: num,
            storeid: storeid,
            classid: this.data.categoryid
          })
        }
        wx.setStorage({
          key: 'updateStoreArry',
          data: storeArry,
        })
      },
      fail: res => {
        storeArry.push({
          goodsid: goodsid,
          goodsnum: num,
          storeid: storeid,
          classid: this.data.categoryid
        })
        wx.setStorage({
          key: 'updateStoreArry',
          data: storeArry,
        })
      }
    })
    app.globalData.isDeleteByStore = false;
  },
  goToCart() {
    if (this.data.isLogin) {
      app.globalData.cartIndexType = 2;
      wx.navigateTo({
        url: '../cart/cartIndexSec',
      })
    } else {
      this.setData({
        showLoginPop: true
      })
    }
  },
  exchangeCoupon() {
    this.setData({
      isExchange: true
    })
    server.postJSON(common.storePath + 'coupon/isexchange/', {
      "score_mall_id": this.data.goodsDetail.score_mall_id
    }, res => {
      this.setData({
        isExchange: false
      })
      if (res.data.errno == '0') {
        this.setData({
          isShowExchange: true
        })
      } else {
        common.showErrorToast(res.data.errmsg);
      }
    })
  },
  hideConfirmCont() {
    this.setData({
      isShowExchange: false
    })
  },
  exchangeGoods(e) {
    this.setData({
      isCanExchange: false
    })
    var param = {
      "score_mall_id": e.currentTarget.dataset.voucherid
    }
    this.confirmExchangeTicket(param);
  },
  getcoupon(params){
    this.setData({
      isCanExchange: false
    })
    var param = {
      "score_mall_id":this.data.goodsDetail.score_mall_id,
      "send_coupon_result": params.detail.send_coupon_result
    }
    this.confirmExchangeTicket(param);
  },
  confirmExchangeTicket(param) {
    server.postJSON(common.storePath + 'coupon/scoremallexchange/', param, res => {
      if (res.data.errno == '0') {
        if(param.send_coupon_result!=undefined||param.send_coupon_result!=''){
          this.getProductDetail()
        }
        this.setData({
          isShowExchange: false,
          isCanExchange: true
        })
        wx.getStorage({
          key: 'userInfo',
          success: resp => {
            resp.data.coupon_num = parseInt(resp.data.coupon_num) + 1;
            wx.setStorage({
              key: "userInfo",
              data: resp.data
            })
          },
        })
        this.addCart();
      } else {
        this.setData({
          isShowExchange: false,
          isCanExchange: true
        })
        common.showErrorToast(res.data.errmsg)
      }
    })
  },
  getRecommendGoods() {
    server.postJSON(common.storePath + 'store/getrecommendgoods/', {
      "store_id": this.data.storeId,
      "recommend_type": 'view_to_view',
      "recommend_num": 10,
      "goods_ids": [
        this.data.goods_id
      ]
    }, res => {
      if (res.data.errno == '0') {
        if (res.data.data.length > 0) {
          (res.data.data).forEach((item, index) => {
            item.isCanAdd = true;
            item.isCanReduce = true;
          })
          this.setData({
            recommendGoods: res.data.data
          })
          if (common.compareVersion(wx.getSystemInfoSync().SDKVersion, '1.9.6') >= 0) {
            this.data.recommendGoods.forEach((item, idx) => {
              let intersect = wx.createIntersectionObserver();
              intersect.relativeToViewport().observe('#easy-rec-' + item.goods_id, (res) => {
                intersect.disconnect(); //使用disconnect，使得目标节点只曝光一次
                server.postJSON(common.storePath + 'store/reportusertrace/', {
                  "store_id": this.data.storeId,
                  "recommend_type": 'view_to_view',
                  "list": [{
                    "goods_id": item.goods_id,
                    "trace_id": item.trace_id,
                    "position": idx
                  }]
                }, res => {
                  if (res.data.errno == '0') {
                    console.log('曝光成功')
                  } else {
                    if (res.data.errno != '100012') {
                      common.showErrorToast(res.data.errmsg)
                    }
                  }
                })
              })
            })
          }
        }

      } else {
        if (res.data.errno != '100012') {
          common.showErrorToast(res.data.errmsg)
        }
      }
    })
  },
  //添加为你推荐商品
  addRecommendCart(e) {
    var index = e.currentTarget.dataset.index;
    this.setData({
      ['recommendGoods[' + index + '].isCanAdd']: false
    })
    if (this.data.isLogin) {
      server.postJSON(common.storePath + 'cart/addgoods/', {
        "store_id": this.data.storeId,
        "goods_id": e.currentTarget.dataset.id,
        "trace_id": e.currentTarget.dataset.traceid,
        "scene": "view_to_view"
      }, res => {
        if (res.data.errno == "0") {
          common.showErrorToast("添加成功");
          this.getCartNum();
          this.setData({
            cartNum: parseInt(this.data.cartNum) + 1,
            ['recommendGoods[' + index + '].isCanAdd']: true,
            ['recommendGoods[' + index + '].cart_num']: parseInt(this.data.recommendGoods[index].cart_num) + 1
          })
        } else {
          this.setData({
            ['recommendGoods[' + index + '].isCanAdd']: true
          })
          common.showErrorToast(res.data.errmsg);
        }
      })
    } else {
      this.setData({
        showLoginPop: true,
        ['recommendGoods[' + index + '].isCanAdd']: true
      })
    }

  },
  addEmpty() {
    console.log('waiting add success')
  },
  //去推荐商品详情页
  goToProductDetail(e) {
    wx.showNavigationBarLoading();
    common.showLoading();
    wx.pageScrollTo({
      scrollTop: 0,
      duration: 300
    })
    var curTarget = e.currentTarget.dataset;
    wx.setStorageSync('curgoodsmesg', {
      'curtraceid': curTarget.traceid,
      'curgoodsscene': this.data.classifySeletedName
    })
    app.globalData.formSceneId = '';
    var param = {
      "goods_id": curTarget.id,
      "city": app.globalData.city,
      "longitude": app.globalData.longitude,
      "latitude": app.globalData.latitude,
      "store_id": this.data.storeId,
      "trace_id": curTarget.traceid == undefined ? '' : curTarget.traceid,
      "scene": 'view_to_view'
    }
    server.postJSON(common.storePath + 'goods/detail/', param, res => {
      var res = res.data;
      if (res.errno == "0") {
        wx.hideNavigationBarLoading();
        common.hideLoading();
        this.setData({
          goodsDetail: res.data
        })
        this.getRecommendGoods();
        if (res.data.cart_num > 0) {
          this.setData({
            isCanReduce: true
          })
        }
        this.setData({
          isCanAdd: true
        })
      } else if (res.errno == "153001") {
        common.showErrorToast(res.errmsg)
        if (this.data.storageStoreid == '' || this.data.storageStoreid == undefined) {
          app.globalData.skipType = 1;
        } else {
          app.globalData.skipType = 2;
        }
        setTimeout(function () {
          wx.switchTab({
            url: '../index/index',
          })
        }, 1000)

      } else {
        common.showErrorToast(res.errmsg)
      }

    })
  },
  hideLoginPop() {
    this.setData({
      showLoginPop: false
    })
  },
  showAgreement() {
    wx.navigateTo({
      url: '../common/agreement',
    })
  }
})